package com.newland.starpos.partner.mvc.interceptor;

import com.alibaba.fastjson.JSON;
import com.newland.starpos.partner.bean.UserInfo;
import com.newland.starpos.partner.exception.CustomException;
import com.newland.starpos.partner.http.ResponseEnum;
import com.newland.starpos.partner.http.ResponseModel;
import com.newland.starpos.partner.service.UserService;
import com.newland.starpos.partner.thread.UserThreadLocal;
import com.newland.starpos.partner.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
public class AccessTokenInterceptor extends HandlerInterceptorAdapter {
	
	@Autowired
	private UserService userService;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		String accessToken = request.getHeader("ACCESS_TOKEN");
		log.info("ACCESS_TOKEN:[{}]", accessToken);
		if (Objects.isNull(accessToken)) {
			throw new CustomException(ResponseEnum.ACCESS_TOKEN_NULL); //一行代码完事,如有问题换回下面方式
			/*String responseData = JSON.toJSONString(new ResponseModel(ResponseEnum.ACCESS_TOKEN_NULL));
			log.info("response data:{}", responseData);
			response.getWriter().write(responseData);
			return false;*/
		}
		UserInfo userInfo = userService.findUserInfo(accessToken);
		if (Objects.isNull(userInfo)) {
			throw new CustomException(ResponseEnum.ACCESS_TOKEN_EXPIRED_OR_INVALID);
			/*String responseData = JSON.toJSONString(new ResponseModel(ResponseEnum.ACCESS_TOKEN_EXPIRED_OR_INVALID));
			log.info("response data:{}", responseData);
			response.getWriter().write(responseData);
			return false;*/
		}
		log.info("ACCESS_TOKEN transform to userId： " + userInfo.getUserId());
		UserThreadLocal.set(userInfo);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

		UserThreadLocal.remove();
	}
}
